import { login, logout, getInfo } from '@/api/apis.js'
import { getToken, setToken, removeToken } from '@/utils/auth.js'

// 定义数据变量
const user = {
  state: {
    token: getToken(),
    name: '',
    avatar: '',
    roles: []
  },


  // 同步更新数据
  mutations: {
    SET_TOKEN: (state, token) => {
      state.token = token
    },
    SET_NAME: (state, name) => {
      state.name = name
    },
    SET_AVATAR: (state, avatar) => {
      state.avatar = avatar
    },
    SET_ROLES: (state, roles) => {
      state.roles = roles
    }
  },

  // 异步提交 mutation
  actions: {
    // 登录
    userLogin({ commit }, userInfo) {
      return new Promise((resolve, reject) => {
        login( userInfo.username, userInfo.password ).then( response => {

          if(100== response.code){
            setToken(response.token)
            commit('SET_TOKEN', response.token)
            resolve()
          }else{
            reject("登录失败")
          }
        }).catch(error => {
          reject(error)
        })
      })
    },

    // 获取用户信息
    GetInfo({ commit, state }) {

      return new Promise((resolve, reject) => {
        getInfo(state.token).then(response => {
          console.log("请求数据前的权限 验证  返回信息=" )
          console.log(  response)
          console.log(  "--------------")
          const data = response.data
          if (data.roles && data.roles.length > 0) {
            commit('SET_ROLES', data.roles)
          } else {
            reject('角色必须要非空数组!')
          }
          commit('SET_NAME', data.name)
          commit('SET_AVATAR', data.avatar)
          resolve(response)
        }).catch(error => {
          reject(error)
        })
      })
    },

    // 用户完全登出 需要服务器反应
    LogOut({ commit, state }) {
      return new Promise((resolve, reject) => {
        logout( state.token).then(() => {
          commit('SET_TOKEN', '')
          commit('SET_ROLES', [])
          removeToken()
          resolve()
        }).catch(error => {
          reject(error)
        })
      })
    },

    // 前端 登出
    FedLogOut({ commit }) {
      return new Promise(resolve => {
        commit('SET_TOKEN', '')
        removeToken()
        resolve()
      })
    }
  }
}

export default user


